#include "SimpleTcpSocketClientDemo.h"
#include <QTcpSocket>
#include <QDebug>
#include <QTime>
#include <Qstring>

//客户端
SimpleTcpSocketClientDemo::SimpleTcpSocketClientDemo()
{
    //1. 创建TCP套接字对象
    m_pTcpSocket = new QTcpSocket(this);
    //2. 已连接、数据可读、失败信号连接
    connect(m_pTcpSocket, &QTcpSocket::connected, this, &SimpleTcpSocketClientDemo::connected);
    connect(m_pTcpSocket, &QIODevice::readyRead, this, &SimpleTcpSocketClientDemo::readyRead);
    typedef void (QAbstractSocket::*QAbstractSocketErrorSignal)(QAbstractSocket::SocketError);
    connect(m_pTcpSocket, static_cast<QAbstractSocketErrorSignal>(&QTcpSocket::error), this, &SimpleTcpSocketClientDemo::error);
    //3. 与服务器端建立连接
    m_pTcpSocket->connectToHost("127.0.0.1", 8888);
    //4. 同步处理-等待数据可读
    //m_pTcpSocket->waitForReadyRead();
    //5.写给服务器数据
    //m_pTcpSocket->waitForBytesWritten();
    m_pTcpSocket->waitForConnected(10000);//等候连接建立
    write();
    m_pTcpSocket->flush();
}

void SimpleTcpSocketClientDemo::readyRead()
{
    qDebug() << "SimpleTcpSocketClientDemo::readyRead " << m_pTcpSocket->readAll();
}
void SimpleTcpSocketClientDemo::write()
{
    QString sWriteData="have a try";//修改这个输入
    qDebug()<<sWriteData;//在客户端展示输入内容
    m_pTcpSocket->write(sWriteData.toUtf8());//写入缓存
    m_pTcpSocket->flush();//清空缓存
}

void SimpleTcpSocketClientDemo::connected()
{
    qDebug() << "SimpleTcpSocketClientDemo::connected  successfully";
}

void SimpleTcpSocketClientDemo::error(QAbstractSocket::SocketError socketError)
{
    qDebug() << "SimpleTcpSocketClientDemo::error " << socketError;
}

void ClientRunnable::run()
{
    //这样写会内存泄漏，如此写方便测试。
    SimpleTcpSocketClientDemo* pSimpleTcpSocketClient = new SimpleTcpSocketClientDemo;
}

#define CLINET_COUNT 1  //客户端的数量
void testSimpleTcpSocketClientDemo()
{
    QTime oTime;
    oTime.start();

    //同步线程池的方式模拟多个客户端与服务器端交互
    for (int nIndex = 0; nIndex < CLINET_COUNT; ++nIndex)
    {
        ClientRunnable* pRunnable = new ClientRunnable;
        pRunnable->setAutoDelete(false);
        QThreadPool::globalInstance()->start(pRunnable);

    }

    QThreadPool::globalInstance()->waitForDone(30 * 1000);
    qDebug() << "connect count: " << CLINET_COUNT << "total time: " << (double)oTime.elapsed() / double(1000) << "s";
}
void testSimpleTcpSocketClientDemo2()
{
    SimpleTcpSocketClientDemo C();
}
